﻿using CDH_VoteSys.Models.Database;
using CDH_VoteSys.Models.Enterprise_Detail;
using CDH_VoteSys.service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Transactions;

namespace CDH_VoteSys.Controllers
{
	/// <summary>
	/// 企业详情
	/// </summary>
	/// <returns></returns>
	[Route("api/[controller]/[action]")]
	[ApiController]
	public class Company_Detail : Controller
	{
		//定义数据库上下文
		private readonly CDH_VoteSysContext _db;
		private readonly IJWTService _jwtService;
		/// <summary>
		/// 构造方法 构造注入
		/// 把数据库上下文初始化
		/// </summary>
		/// <param name="db"></param>
		/// <param name="jwtService"></param>
		public Company_Detail(CDH_VoteSysContext db, IJWTService jwtService = null)
		{
			_db = db;
			_jwtService = jwtService;
		}

		/// <summary>
		/// 获取企业详情（投票项目详情）项目需审核通过后才能被投票和在列表展示
		/// </summary>
		/// <param name="Com_Id"></param>
		/// <returns></returns>
		/// 返回连表后的模型数据
		/// 信息接口 输入：投票项目Id 
		/// 输出：所需内容字段
		[HttpPost]
		public List<Company_Detail_Check> Detail_Checks(int Com_Id)
		{
			//获取企业详情
			var CompanyDetail = _db.CompanyDataUploads.AsQueryable();
			//判断查询的项目id>0
			if (Com_Id > 0)
			{
				CompanyDetail = CompanyDetail.Where(x => x.ComId == Com_Id);
			}
			//判断企业项目审核状态
			//捕抓异常
			try
			{
				CompanyDetail = CompanyDetail.Where(x => x.ReviewStatus == 1);
			}
			catch (Exception e)
			{
				Console.WriteLine("未审核或已审核");
				throw e;
			}
			//开始连表            连接表           主表外键      连接表的主键    把两个表的字段结合起来 新建一个模型
			var list = CompanyDetail.Join(_db.Awards, x => x.ComId, y => y.ComId, (x, y) => new Company_Detail_Check
			{
				Com_Logo = x.ComLogo,
				Com_Name = x.ComName,
				Com_Introduction = x.ComIntroduction,
				Com_AwardTime = y.ComAwardTime,
				Award_Type = y.AwardType,
				Project_pic1 = y.ProPic1,
				Project_pic2 = y.ProPic2,
				Project_pic3 = y.ProPic3,
				Project_pic4 = y.ProPic4,
				Project_pic5 = y.ProPic5
			}).ToList();
			return list;
		}

		/// <summary>
		/// 投票接口（需授权）
		/// </summary>
		/// <param name="Com_Id"></param>
		/// <returns></returns>
		/// 每个人每天可投5票
		/// 输入：投票项目Id
		/// 输出：投票结果消息
		[HttpPost]
		[Authorize]
		public string Vote(int Com_Id)
		{
			//开启事务锁 保证数据的一致性 死锁
			using (var scope = new TransactionScope())
			{
				try
				{
					//获取当前用户
					var uid = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
					//获取公司的投票数
					var companyVote = _db.CompanyDataUploads.FirstOrDefault(x => x.ComId == Com_Id);
					//判断用户是否登录
					if (uid == null)
					{
						return "请先登录";
					}
					//获取当前时间
					var now = DateTime.Now;
					//获取当天时间
					var today = now.Date;
					//获取用户当天投票次数
					var count = _db.Votes.Count(x => x.Uid == int.Parse(uid) && x.CreateTime >= today);
					//判断该项目是否存在
					if (companyVote == null)
					{
						return "该项目不存在";
					}
					//判断该项目是否审核通过
					if (companyVote.ReviewStatus != 1)
					{
						return "该项目未审核通过，不能投票";
					}
					//判断用户当天投票次数
					if (count > 5)
					{
						return "今天投票次数已用完";
					}
					//添加投票记录，并且通过连接公司表，每一次添加投票记录，公司的投票数加1
					_db.Votes.Add(new Vote
					{
						Uid = int.Parse(uid),
						ComId = Com_Id,
						CreateTime = now
					});
					//投票数加1
					companyVote.Vnum++;
					//保存数据
					var row = _db.SaveChanges();
					if (row > 0)
					{
						scope.Complete();
						//返回投票成功
						return "投票成功";
					}
					return "投票失败";
				}
				catch (Exception ex)
				{
					scope.Dispose();
					return "投票失败";
				}
			}
		}
	}
}
